Imports System.Data.SqlClient
Imports System.ComponentModel

Public Class cls_caja_

    Implements ICloneable

#Region "Variables ..."
    Private int_idcaja As Integer = 0
    Private dte_fecha As DateTime = New System.DateTime(Now.Year, 1, 1)
    Private dbl_saldo As Double = 0
    Private int_tipo As enu_tipo = 0
    Private int_idregistro As Integer = 0

    Private obj_registro As cls_registro_ = Nothing
    Private obj_cajaasiento_ As cls_cajaasiento_ = Nothing

    Private col_Items As Collections.Generic.List(Of cls_caja_) = Nothing


    Public Enum enu_tipo
        <Description("Todas las Cajas")> General = 0
        <Description("Mostrador")> Mostrador = 1
        <Description("Reparto")> Reparto = 2
    End Enum

    Public Overrides Function ToString() As String
        Return fecha.ToShortDateString
    End Function
#End Region

#Region "Propiedades ..."
    Property idcaja() As Integer
        Get
            idcaja = int_idcaja
        End Get
        Set(ByVal value As Integer)
            int_idcaja = value
        End Set
    End Property
    Property fecha() As DateTime
        Get
            fecha = dte_fecha
        End Get
        Set(ByVal value As DateTime)
            dte_fecha = value
        End Set
    End Property
    Property saldo() As Double
        Get
            saldo = dbl_saldo
        End Get
        Set(ByVal value As Double)
            dbl_saldo = value
        End Set
    End Property
    Property tipo() As enu_tipo
        Get
            tipo = int_tipo
        End Get
        Set(ByVal value As enu_tipo)
            int_tipo = value
        End Set
    End Property
    Property idregistro() As Integer
        Get
            idregistro = int_idregistro
        End Get
        Set(ByVal value As Integer)
            int_idregistro = value
        End Set
    End Property
    Property cajaasiento_() As cls_cajaasiento_
        Get
            If IsNothing(obj_cajaasiento_) Then
                obj_cajaasiento_ = New cls_cajaasiento_
                If Not obj_cajaasiento_.CargarXidcaja(idcaja) Then
                    obj_cajaasiento_ = Nothing
                End If
            End If
            cajaasiento_ = obj_cajaasiento_
        End Get
        Set(ByVal value As cls_cajaasiento_)
            obj_cajaasiento_ = value
        End Set
    End Property
    Property registro() As cls_registro_
        Get
            If IsNothing(obj_registro) Then
                obj_registro = New cls_registro_
                If Not obj_registro.Buscar(idregistro) Then
                    obj_registro = Nothing
                End If
            End If
            registro = obj_registro
        End Get
        Set(ByVal value As cls_registro_)
            obj_registro = value
        End Set
    End Property
    Property Items() As Collections.Generic.List(Of cls_caja_)
        Get
            Items = col_Items
        End Get
        Set(ByVal value As Collections.Generic.List(Of cls_caja_))
            col_Items = value
        End Set
    End Property
#End Region

    Private Sub CargarColeccion(ByVal obj_Reader As SqlDataReader)
        col_Items = New Collections.Generic.List(Of cls_caja_)
        While obj_Reader.Read()
            Dim Elemento As New cls_caja_
            Elemento.int_idcaja = (obj_Reader.GetValue(obj_Reader.GetOrdinal("idcaja")))

            If IsDBNull(obj_Reader.GetValue(obj_Reader.GetOrdinal("fecha"))) = False Then
                Elemento.dte_fecha = (obj_Reader.GetValue(obj_Reader.GetOrdinal("fecha")))
            End If
            If IsDBNull(obj_Reader.GetValue(obj_Reader.GetOrdinal("saldo"))) = False Then
                Elemento.dbl_saldo = (obj_Reader.GetValue(obj_Reader.GetOrdinal("saldo")))
            End If
            If IsDBNull(obj_Reader.GetValue(obj_Reader.GetOrdinal("tipo"))) = False Then
                Elemento.int_tipo = (obj_Reader.GetValue(obj_Reader.GetOrdinal("tipo")))
            End If
            If IsDBNull(obj_Reader.GetValue(obj_Reader.GetOrdinal("idregistro"))) = False Then
                Elemento.int_idregistro = (obj_Reader.GetValue(obj_Reader.GetOrdinal("idregistro")))
            End If
            col_Items.Add(Elemento)
        End While
    End Sub

    Private Sub CargarVariables(ByVal obj_Reader As SqlDataReader)
        obj_Reader.Read()
        int_idcaja = (obj_Reader.GetValue(obj_Reader.GetOrdinal("idcaja")))

        If IsDBNull(obj_Reader.GetValue(obj_Reader.GetOrdinal("fecha"))) = False Then
            dte_fecha = (obj_Reader.GetValue(obj_Reader.GetOrdinal("fecha")))
        End If
        If IsDBNull(obj_Reader.GetValue(obj_Reader.GetOrdinal("saldo"))) = False Then
            dbl_saldo = (obj_Reader.GetValue(obj_Reader.GetOrdinal("saldo")))
        End If
        If IsDBNull(obj_Reader.GetValue(obj_Reader.GetOrdinal("tipo"))) = False Then
            int_tipo = (obj_Reader.GetValue(obj_Reader.GetOrdinal("tipo")))
        End If
        If IsDBNull(obj_Reader.GetValue(obj_Reader.GetOrdinal("idregistro"))) = False Then
            int_idregistro = (obj_Reader.GetValue(obj_Reader.GetOrdinal("idregistro")))
        End If
    End Sub

    Public Sub Nuevo(Optional ByVal ObtenerID As Boolean = False)
        Dim obj_Conexion As New cls_Conexion
        Try

            'Creacion de registro----------------------------------------------------
            If IsNothing(obj_registro) Then
                registro = New cls_registro_
                registro.fechacreado = Now
                registro.idusuariocreado = UsuarioLOG.idusuario
                registro.fechamodificado = Now
                registro.idusuariomodificado = UsuarioLOG.idusuario
                registro.idregistroestado = 1
                registro.idusuarioregistroestado = UsuarioLOG.idusuario
                registro.Nuevo(True)
                idregistro = obj_registro.idregistro
            End If
            '------------------------------------------------------------------------

            obj_Conexion.Conectar()
            With obj_Conexion.obj_SqlCommand
                .CommandType = CommandType.StoredProcedure
                .Connection = obj_Conexion.obj_SqlConnection
                .CommandText = "caja__Nuevo"
                .Parameters.Add("@fecha", SqlDbType.DateTime).Value = dte_fecha.Date
                .Parameters.Add("@saldo", SqlDbType.Decimal).Value = dbl_saldo
                .Parameters.Add("@tipo", SqlDbType.Int).Value = int_tipo
                .Parameters.Add("@idregistro", SqlDbType.Int).Value = int_idregistro
                .ExecuteNonQuery()
            End With
            CargarUltimo()

            'Creacion de cajaasiento_--------------------------------------------------
            If Not IsNothing(cajaasiento_) Then
                If Not IsNothing(cajaasiento_.Items) Then
                    For Each cajaasiento As cls_cajaasiento_ In cajaasiento_.Items
                        cajaasiento.idcaja = idcaja
                        cajaasiento.Nuevo(True)
                    Next
                End If
            End If
            '-------------------------------------------------------------------------

        Catch ex As SqlClient.SqlException
            MessageBox.Show("Error al Crear el registro de caja_." & Chr(13) & _
            "Por favor informe del siguiente detalle técnico:" & Chr(13) & _
            "Nro de error: " & ex.ErrorCode & "." & Chr(13) & _
            "Descripción: " & ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            obj_Conexion.Desconectar()
            obj_Conexion = Nothing
        End Try
    End Sub

    Public Sub Modificar()
        Dim obj_Conexion As New cls_Conexion
        Try

            'Modificacion de registro------------------------------------------------
            registro.fechamodificado = Now : registro.idusuariomodificado = UsuarioLOG.idusuario
            registro.Modificar()
            '------------------------------------------------------------------------


            obj_Conexion.Conectar()
            With obj_Conexion.obj_SqlCommand
                .CommandType = CommandType.StoredProcedure
                .Connection = obj_Conexion.obj_SqlConnection
                .CommandText = "caja__Modificar"
                .Parameters.Add("@idcaja", SqlDbType.Int).Value = int_idcaja
                .Parameters.Add("@fecha", SqlDbType.DateTime).Value = dte_fecha.Date
                .Parameters.Add("@saldo", SqlDbType.Decimal).Value = dbl_saldo
                .Parameters.Add("@tipo", SqlDbType.Int).Value = int_tipo
                .Parameters.Add("@idregistro", SqlDbType.Int).Value = int_idregistro
                .ExecuteNonQuery()
            End With

            'Creacion/modificacion de cajaasiento-------------------------------------
            If Not IsNothing(cajaasiento_) Then
                If Not IsNothing(cajaasiento_.Items) Then
                    For Each cajaasiento As cls_cajaasiento_ In cajaasiento_.Items
                        If cajaasiento.idcajaasiento = 0 Then
                            cajaasiento.idcaja = idcaja
                            cajaasiento.Nuevo(True)
                        Else
                            cajaasiento.Modificar()
                        End If
                    Next
                End If
            End If
            '-------------------------------------------------------------------------

        Catch ex As SqlClient.SqlException
            MessageBox.Show("Error al Modificar el registro de caja_." & Chr(13) & _
            "Por favor informe del siguiente detalle técnico:" & Chr(13) & _
            "Nro de error: " & ex.ErrorCode & "." & Chr(13) & _
            "Descripción: " & ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            obj_Conexion.Desconectar()
            obj_Conexion = Nothing
        End Try
    End Sub

    Public Sub Eliminar(ByVal idcaja As Integer)
        Dim obj_Conexion As New cls_Conexion
        Try
            obj_Conexion.Conectar()
            With obj_Conexion.obj_SqlCommand
                .CommandType = CommandType.StoredProcedure
                .Connection = obj_Conexion.obj_SqlConnection
                .CommandText = "caja__Eliminar"
                .Parameters.Add("@idcaja", SqlDbType.Int).Value = idcaja
                .ExecuteNonQuery()
            End With
        Catch ex As SqlClient.SqlException
            MessageBox.Show("Error al Eliminar el registro de caja_." & Chr(13) & _
            "Por favor informe del siguiente detalle técnico:" & Chr(13) & _
            "Nro de error: " & ex.ErrorCode & "." & Chr(13) & _
            "Descripción: " & ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            obj_Conexion.Desconectar()
            obj_Conexion = Nothing
        End Try
    End Sub

    Public Function Buscar(ByVal idcaja As Integer) As Boolean
        Dim obj_Conexion As New cls_Conexion
        Dim obj_Reader As SqlDataReader
        Try
            Buscar = False
            obj_Conexion.Conectar()
            With obj_Conexion.obj_SqlCommand
                .CommandType = CommandType.StoredProcedure
                .Connection = obj_Conexion.obj_SqlConnection
                .CommandText = "caja__Buscar"
                .Parameters.Add("@idcaja", SqlDbType.Int).Value = idcaja
            End With
            obj_Reader = obj_Conexion.obj_SqlCommand.ExecuteReader
            If obj_Reader.HasRows Then
                CargarVariables(obj_Reader)
                Buscar = True
            End If
        Catch ex As SqlClient.SqlException
            MessageBox.Show("Error al Buscar el registro de caja_." & Chr(13) & _
            "Por favor informe del siguiente detalle técnico:" & Chr(13) & _
            "Nro de error: " & ex.ErrorCode & "." & Chr(13) & _
            "Descripción: " & ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            obj_Conexion.Desconectar()
            obj_Conexion = Nothing
            obj_Reader = Nothing
        End Try
    End Function

    Public Function BuscarXfecha(ByVal prm_fecha As DateTime) As Boolean
        Dim obj_Conexion As New cls_Conexion
        Dim obj_Reader As SqlDataReader
        Try
            BuscarXfecha = False
            obj_Conexion.Conectar()
            With obj_Conexion.obj_SqlCommand
                .CommandType = CommandType.StoredProcedure
                .Connection = obj_Conexion.obj_SqlConnection
                .CommandText = "caja__BuscarXfecha"
                .Parameters.Add("@fecha", SqlDbType.DateTime).Value = prm_fecha
            End With
            obj_Reader = obj_Conexion.obj_SqlCommand.ExecuteReader
            If obj_Reader.HasRows Then
                CargarVariables(obj_Reader)
                BuscarXfecha = True
            End If
        Catch ex As SqlClient.SqlException
            MessageBox.Show("Error al BuscarXfecha el registro de caja_." & Chr(13) & _
            "Por favor informe del siguiente detalle técnico:" & Chr(13) & _
            "Nro de error: " & ex.ErrorCode & "." & Chr(13) & _
            "Descripción: " & ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            obj_Conexion.Desconectar()
            obj_Conexion = Nothing
            obj_Reader = Nothing
        End Try
    End Function

    Public Function BuscarXfechaXtipo(ByVal prm_fecha As DateTime, ByVal prm_tipo As enu_tipo) As Boolean
        Dim obj_Conexion As New cls_Conexion
        Dim obj_Reader As SqlDataReader
        Try
            BuscarXfechaXtipo = False
            obj_Conexion.Conectar()
            With obj_Conexion.obj_SqlCommand
                .CommandType = CommandType.StoredProcedure
                .Connection = obj_Conexion.obj_SqlConnection
                .CommandText = "caja__BuscarXfechaXtipo"
                .Parameters.Add("@fecha", SqlDbType.DateTime).Value = prm_fecha.Date
                .Parameters.Add("@tipo", SqlDbType.Int).Value = prm_tipo
            End With
            obj_Reader = obj_Conexion.obj_SqlCommand.ExecuteReader
            If obj_Reader.HasRows Then
                CargarVariables(obj_Reader)
                BuscarXfechaXtipo = True
            End If
        Catch ex As SqlClient.SqlException
            MessageBox.Show("Error al BuscarXfecha el registro de caja_." & Chr(13) & _
            "Por favor informe del siguiente detalle técnico:" & Chr(13) & _
            "Nro de error: " & ex.ErrorCode & "." & Chr(13) & _
            "Descripción: " & ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            obj_Conexion.Desconectar()
            obj_Conexion = Nothing
            obj_Reader = Nothing
        End Try
    End Function

    Public Sub CargarUltimo()
        Dim obj_Conexion As New cls_Conexion
        Dim obj_Reader As SqlDataReader
        Try
            obj_Conexion.Conectar()
            With obj_Conexion.obj_SqlCommand
                .CommandType = CommandType.StoredProcedure
                .Connection = obj_Conexion.obj_SqlConnection
                .CommandText = "caja__CargarUltimo"
            End With
            obj_Reader = obj_Conexion.obj_SqlCommand.ExecuteReader
            If obj_Reader.HasRows Then
                CargarVariables(obj_Reader)
            End If
        Catch ex As SqlClient.SqlException
            MessageBox.Show("Error al CargarUltimo registro de caja_." & Chr(13) & _
            "Por favor informe del siguiente detalle técnico:" & Chr(13) & _
            "Nro de error: " & ex.ErrorCode & "." & Chr(13) & _
            "Descripción: " & ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            obj_Conexion.Desconectar()
            obj_Conexion = Nothing
            obj_Reader = Nothing
        End Try
    End Sub

    Public Function CargarTodos() As Boolean
        Dim obj_Conexion As New cls_Conexion
        Dim obj_Reader As SqlDataReader
        Try
            CargarTodos = False
            obj_Conexion.Conectar()
            With obj_Conexion.obj_SqlCommand
                .CommandType = CommandType.StoredProcedure
                .Connection = obj_Conexion.obj_SqlConnection
                .CommandText = "caja__CargarTodos"
            End With
            obj_Reader = obj_Conexion.obj_SqlCommand.ExecuteReader
            If obj_Reader.HasRows Then
                CargarColeccion(obj_Reader)
                CargarTodos = True
            End If
        Catch ex As SqlClient.SqlException
            MessageBox.Show("Error al CargarTodos los registros de caja_." & Chr(13) & _
            "Por favor informe del siguiente detalle técnico:" & Chr(13) & _
            "Nro de error: " & ex.ErrorCode & "." & Chr(13) & _
            "Descripción: " & ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            obj_Conexion.Desconectar()
            obj_Conexion = Nothing
            obj_Reader = Nothing
        End Try
    End Function

    Public Function CargarXtipo(ByVal prm_tipo As enu_tipo, Optional ByVal idregistroestado As Integer = 1) As Boolean
        Dim obj_Conexion As New cls_Conexion
        Dim obj_Reader As SqlDataReader
        Try
            CargarXtipo = False
            obj_Conexion.Conectar()
            With obj_Conexion.obj_SqlCommand
                .CommandType = CommandType.StoredProcedure
                .Connection = obj_Conexion.obj_SqlConnection
                .CommandText = "caja__CargarXtipo"
                .Parameters.Add("@tipo", SqlDbType.Int).Value = prm_tipo
                .Parameters.Add("@idregistroestado", SqlDbType.Int).Value = idregistroestado
            End With
            obj_Reader = obj_Conexion.obj_SqlCommand.ExecuteReader
            If obj_Reader.HasRows Then
                CargarColeccion(obj_Reader)
                CargarXtipo = True
            End If
        Catch ex As SqlClient.SqlException
            MessageBox.Show("Error al CargarXtipo los registros de caja_." & Chr(13) & _
            "Por favor informe del siguiente detalle técnico:" & Chr(13) & _
            "Nro de error: " & ex.ErrorCode & "." & Chr(13) & _
            "Descripción: " & ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            obj_Conexion.Desconectar()
            obj_Conexion = Nothing
            obj_Reader = Nothing
        End Try
    End Function

    Public Function Clone() As Object Implements System.ICloneable.Clone
        Dim obj_caja_Clon As New cls_caja_
        obj_caja_Clon.int_idcaja = Me.int_idcaja
        obj_caja_Clon.dte_fecha = Me.dte_fecha
        obj_caja_Clon.dbl_saldo = Me.dbl_saldo
        obj_caja_Clon.int_tipo = Me.int_tipo
        obj_caja_Clon.int_idregistro = Me.int_idregistro
        obj_caja_Clon.col_Items = Me.col_Items
        Return obj_caja_Clon
    End Function

    Public Function total() As Decimal
        Dim dec_total As Decimal = saldo
        If Not IsNothing(cajaasiento_) Then
            If Not IsNothing(cajaasiento_.Items) Then
                For Each cajaasiento As cls_cajaasiento_ In cajaasiento_.Items
                    Select Case cajaasiento.tipoimporte
                        Case cls_cajaasiento_.enu_tipoimporte.Ingreso
                            dec_total += cajaasiento.importe
                        Case cls_cajaasiento_.enu_tipoimporte.Salida
                            dec_total -= cajaasiento.importe
                    End Select
                Next
            End If
        End If
        Return dec_total
    End Function
End Class
